package com.aiwu.dialog

import android.content.DialogInterface
import android.view.View
import androidx.annotation.StringRes
import android.util.Pair
import com.aiwu.MyApp
import com.aiwu.library.AiwuSimulator
import com.aiwu.library.abs.ui.AbsQuickSettingDialog
import com.aiwu.library.bean.setting.SeekBarSettingBean
import com.aiwu.library.bean.setting.SelectItemPairBean
import com.aiwu.library.bean.setting.SelectSettingBean
import com.aiwu.library.bean.setting.SwitchCommonSettingBean
import com.aiwu.library.bean.setting.TextSettingBean
import com.aiwu.library.ui.adapter.SettingMultipleTypeAdapter
import com.aiwu.library.util.ClipboardUtil
import com.aiwu.library.util.DialogUtil
import com.aiwu.library.util.LogUtil
import com.aiwu.library.util.ToastUtil
import com.aiwu.utils.InitFileUtil
import com.aiwu.utils.PrefsHelper
import com.aiwu.utils.getBooleanValue
import com.aiwu.utils.saveValue
import com.aiwu.utils.saveValueAsBoolean
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import org.citra.citra_emu.NativeLibrary
import org.citra.citra_emu.R
import org.citra.citra_emu.activities.EmulationActivity
import org.citra.citra_emu.display.ScreenAdjustmentUtil
import org.citra.citra_emu.features.settings.model.AbstractSetting
import org.citra.citra_emu.features.settings.model.BooleanSetting
import org.citra.citra_emu.features.settings.model.IntSetting
import org.citra.citra_emu.features.settings.ui.SettingsActivity
import org.citra.citra_emu.features.settings.utils.SettingsFile
import org.citra.citra_emu.fragments.EmulationFragment
import org.citra.citra_emu.utils.EmulationMenuSettings

/**
 * 快捷设置
 */
class FastSettingDialog(
    private val emulationActivity: EmulationActivity,
    private val emulationFragment: EmulationFragment,
    private val screenAdjustmentUtil: ScreenAdjustmentUtil
) : AbsQuickSettingDialog<SettingMultipleTypeAdapter>(emulationActivity) {

    private var reloadSettings = false
    private val textureFilterValues by lazy {
        context.resources.getIntArray(R.array.textureFilterValues)
    }

    override fun doLogic() {
        super.doLogic()
        settingAdapter.run {
            setOnItemClickListener { _: BaseQuickAdapter<*, *>?, _: View?, position: Int ->
                val item = settingAdapter.getItem(position) as? TextSettingBean
                    ?: return@setOnItemClickListener
                val title = item.title
                when (title) {
                    getString(R.string.game_id) -> {
                        ClipboardUtil.copyText(item.currentText, true)
                    }

                    getString(R.string.emulation_switch_screen_layout) -> {
                        dismiss()
                        SwitchScreenLayoutDialog(
                            context,
                            emulationActivity
                        ).show()
                    }

                    getString(R.string.more_setting) -> {
                        dismiss()
                        SettingsActivity.launch(context, SettingsFile.FILE_NAME_CONFIG, "")
                    }
                }
            }
            onItemCheckedListener =
                SettingMultipleTypeAdapter.OnItemCheckedListener { position: Int, isChecked: Boolean ->
                    val item = settingAdapter.getItem(position) as? SwitchCommonSettingBean
                        ?: return@OnItemCheckedListener
                    val title = item.title
                    when (title) {
                        getString(R.string.emulation_swap_screens) -> {
                            screenAdjustmentUtil.swapScreen()
                        }

                        getString(R.string.font_acg) -> {
                            changeFont(position, isChecked)
                        }

                        getString(R.string.emu_lib_menu_sound) -> {
                            IntSetting.AUDIO_OUTPUT_TYPE.saveValueAsBoolean(isChecked, 0, 1)
                            reloadSettings = true
                            AiwuSimulator.setSoundEnable(isChecked)
                        }

                        getString(R.string.quick_bottom_screen) -> {
                            PrefsHelper.instance.setQuickSwitchBottomScreen(isChecked)
                            emulationFragment.refreshFloatingSwitchBottomScreenLayout()
                        }

                        getString(R.string.quick_screen_layout) -> {
                            if (isChecked) {
                                QuickScreenLayoutDialog(context, this@FastSettingDialog).show()
                            } else {
                                PrefsHelper.instance.removeQuickScreenLayout()
                            }
                        }

                        else -> {
                            when (val setting = item.extraObject as? AbstractSetting) {
                                is BooleanSetting -> {
                                    setting.saveValue(isChecked)
                                    reloadSettings = true
                                }

                                is IntSetting -> {
                                    setting.saveValueAsBoolean(isChecked)
                                    reloadSettings = true
                                }

                                else -> {
                                    LogUtil.e("未处理的设置类型:${setting}")
                                }
                            }
                        }
                    }
                }
            onSeekBarItemChangeListener =
                SettingMultipleTypeAdapter.OnSeekBarItemChangeListener { position: Int, progress: Int ->
                    val item = settingAdapter.getItem(position) as? SeekBarSettingBean
                        ?: return@OnSeekBarItemChangeListener
//                    val title = item.title
                    val setting = item.extraObject as? AbstractSetting
                    if (setting is IntSetting) {
                        setting.saveValue(progress)
                        reloadSettings = true
                    }
                }
            onSelectItemChangeListener =
                SettingMultipleTypeAdapter.OnSelectItemChangeListener { position: Int, newSelectItemIndex: Int ->
                    val item = settingAdapter.getItem(position) as? SelectSettingBean<*>
                        ?: return@OnSelectItemChangeListener
                    val title = item.title
                    val setting = item.extraObject as? AbstractSetting
                    when (title) {
                        getString(R.string.menu_emulation_amiibo) -> {
                            if (newSelectItemIndex == 0) {
                                dismiss()
                                emulationFragment.loadAmiibo()
                            } else {
                                NativeLibrary.removeAmiibo()
                                ToastUtil.toast(R.string.amiibo_remove_tip)
                            }
                        }

                        getString(R.string.texture_filter_name) -> {
                            if (setting is IntSetting) {
                                setting.saveValue(textureFilterValues[newSelectItemIndex])
                                reloadSettings = true
                            }
                        }
                    }
                }
        }
    }

    //切换字体
    private fun changeFont(adapterPosition: Int, isAcgFont: Boolean) {
        //需要切换字体
        val success = InitFileUtil.changeFont(isAcgFont)
        if (success) {
            PrefsHelper.instance.setAcgFont(isAcgFont)
            //弹窗提示要不重新开始游戏
            DialogUtil.showTip(
                context, "切换字体成功，是否重启游戏以适用字体？",
                {
                    dismiss()
                    NativeLibrary.resetGame25()
                }, null
            )
        } else {
            ToastUtil.toast("切换字库失败")
            settingAdapter.notifyItemChanged(adapterPosition)
        }
    }

    override fun getSettingAdapter(): SettingMultipleTypeAdapter = SettingMultipleTypeAdapter()

    override fun getSettingData(): List<MultiItemEntity> {
        return ArrayList<MultiItemEntity>().apply {
            add(TextSettingBean(getString(R.string.game_id), MyApp.getRunningGameId()))
            //amiibo
            val amiiboList = arrayListOf(
                SelectItemPairBean(Pair(getString(R.string.menu_emulation_amiibo_load), 0)),
                SelectItemPairBean(Pair(getString(R.string.menu_emulation_amiibo_remove), 1))
            )
            val amiibo = SelectSettingBean<SelectItemPairBean<Int>>(
                getString(R.string.menu_emulation_amiibo), null, null, amiiboList, true, false
            )
            add(amiibo)
            //音频
            add(
                SwitchCommonSettingBean(
                    getString(R.string.emu_lib_menu_sound),
                    null, IntSetting.AUDIO_OUTPUT_TYPE,
                    IntSetting.AUDIO_OUTPUT_TYPE.int != 1,
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.audio_stretch),
                    getString(R.string.audio_stretch_description),
                    IntSetting.ENABLE_AUDIO_STRETCHING,
                    IntSetting.ENABLE_AUDIO_STRETCHING.getBooleanValue()
                )
            )
            //视频
            add(
                SeekBarSettingBean(
                    getString(R.string.internal_resolution),
                    getString(R.string.internal_resolution_description),
                    IntSetting.RESOLUTION_FACTOR.int,
                    1,
                    10,
                    "x"
                ).apply {
                    extraObject = IntSetting.RESOLUTION_FACTOR
                }
            )
            add(TextSettingBean(getString(R.string.emulation_switch_screen_layout), true))
            add(
                SwitchCommonSettingBean(
                    getString(R.string.quick_screen_layout),
                    PrefsHelper.instance.isQuickScreenLayout()
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.quick_bottom_screen),
                    PrefsHelper.instance.isQuickSwitchBottomScreen()
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.emulation_swap_screens),
                    EmulationMenuSettings.swapScreens
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.async_shaders),
                    getString(R.string.async_shaders_description),
                    BooleanSetting.ASYNC_SHADERS,
                    BooleanSetting.ASYNC_SHADERS.boolean
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.linear_filtering),
                    getString(R.string.linear_filtering_description),
                    IntSetting.LINEAR_FILTERING,
                    IntSetting.LINEAR_FILTERING.getBooleanValue()
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.shaders_accurate_mul),
                    getString(R.string.shaders_accurate_mul_description),
                    IntSetting.SHADERS_ACCURATE_MUL,
                    IntSetting.SHADERS_ACCURATE_MUL.getBooleanValue()
                )
            )
            add(
                SwitchCommonSettingBean(
                    getString(R.string.use_disk_shader_cache),
                    getString(R.string.use_disk_shader_cache_description),
                    IntSetting.DISK_SHADER_CACHE,
                    IntSetting.DISK_SHADER_CACHE.getBooleanValue()
                )
            )
            //滤镜
            val textureFilterList =
                context.resources.getStringArray(R.array.textureFilterNames)
                    .mapIndexed { index, str ->
                        SelectItemPairBean(Pair(str, textureFilterValues[index]))
                    }
            val textureFilter = SelectSettingBean<SelectItemPairBean<Int>>(
                getString(R.string.texture_filter_name),
                getString(R.string.texture_filter_description),
                IntSetting.TEXTURE_FILTER,
                textureFilterList,
                IntSetting.TEXTURE_FILTER.int
            )
            add(textureFilter)
            add(
                SwitchCommonSettingBean(
                    getString(R.string.font_acg),
                    getString(R.string.font_acg_desc),
                    PrefsHelper.instance.isAcgFont()
                )
            )
            add(TextSettingBean(getString(R.string.more_setting), true))
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        if (reloadSettings) {
            NativeLibrary.reloadSettings()
        }
        emulationFragment.refreshFloatingScreenLayout()
    }

    /**
     * 刷新快速切换屏幕布局
     */
    fun refreshQuickScreenLayout(isOn: Boolean) {
        for (i in 0 until settingAdapter.itemCount) {
            val item = settingAdapter.getItem(i) as? SwitchCommonSettingBean ?: continue
            if (item.title == getString(R.string.quick_screen_layout)) {
                item.isOn = isOn
                settingAdapter.notifyItemChanged(i)
                break
            }
        }
    }

    private fun getString(@StringRes resId: Int): String {
        return context.getString(resId)
    }
}